﻿using Blm.PgsqlDriver.Helpers;
using Blm.RabbitMQ.MessageQueue;
using Meta.RabbitMQ.Generic;
using Microsoft.Extensions.Logging;
using Npgsql;
using NpgsqlTypes;
using RabbitMQ.Client;
using System;
using System.Threading.Tasks;
using VisionCloud.Domain.DtoModel.RabbitMq;
using VisionCloud.Domain.Repository.Interface.Ms;
using VisionCloud.Domain.UnitOfWork;
using VisionCloud.Utility.Extensions;

namespace VisionCloud.Web.Service.MQListener
{
    public class UpdatePointCompletedBackgroundService : BlmRabbitMQStorageSubscriberBase<TaskPointCompletedDto>
    {
        private readonly ILogger<UpdatePointCompletedBackgroundService> logger;
        private readonly IMsTaskRepository msTaskRepository;

        public UpdatePointCompletedBackgroundService(IServiceProvider serviceProvider,
            ILogger<UpdatePointCompletedBackgroundService> logger,
            IMsTaskRepository msTaskRepository,
            IUnitOfWork unitOfWork) : base(serviceProvider)
        {
            this.logger = logger;
            this.msTaskRepository = msTaskRepository;
        }

        public override ClientOption ClientOption => new ClientOption("visioncloud.pointCompleted.update.ex", "visioncloud.pointCompleted.update.rk", ExchangeType.Topic, "visioncloud.pointCompleted.update.queue", RabbitMQConnectPoolName.CloudServerHost);

        public override async Task InvokeAsync(TaskPointCompletedDto model)
        {
            try
            {
                var taskInfo = await msTaskRepository.FirstOrDefaultAsync(x => x.TaskId == model.TaskId);
                if (taskInfo == null)
                {
                    logger.LogInformation("UpdatePointCompletedBackgroundService：任务不存在");
                }
                if (taskInfo.MeasureAPP != Core.Model.Enums.MeasureAPPEnum.平板端)
                {
                    var updateSql = @"UPDATE ""MsPointCompleted"" t SET ""ComputeCompletedDate""  = @finishdate WHERE t.""TaskId"" = @taskid and t.""PointIndex"" = @PointIndex;
                                      UPDATE tasktable x SET completiontime = @nowstr WHERE x.uuid = @taskid;
                                      UPDATE ""MsTask"" y SET completiontime = @finishdate WHERE y.""TaskId"" = @taskid;";
                    var parameters = new NpgsqlParameter[]
                    {
                       new NpgsqlParameter("finishdate",model.FinishTime){NpgsqlDbType=NpgsqlDbType.Date},
                       new NpgsqlParameter("taskid",model.TaskId){NpgsqlDbType=NpgsqlDbType.Uuid},
                       new NpgsqlParameter("PointIndex",model.PointIndex),
                       new NpgsqlParameter("nowstr",model.FinishTime.ToStanderTimeString())
                    };

                    _ = PgSqlHelper.Transaction(updateSql, parameters);
                }
            }
            catch (Exception ex)
            {
                logger.LogError($"UpdatePointCompletedBackgroundService消费者报错：{ex.Message}，{ex.StackTrace}");
            }
        }
    }
}
